<?php

class AppController extends Controller{
    var $helpers = array('Html', 'Form', 'Display', 'Session', 'Date');
    var $uses = array(
        'User'
    );
    
    var $components = array(
        'Session',
        'Auth' => array( 
            'authError' => 'Did you really think you are allowed to see that?',
            'authenticate' => array(
                'Form' => array(
                    'fields' => array('username' => 'email')
                )
            ),
            'authorize' => array('Controller'),
            'loginRedirect' => array('controller' => 'users', 'action' => 'home')
        ),
        'RequestHandler'
    );
    
    function isAuthorized($user) {       
        return true;
    }
    
    
    public function getCurrentUserId(){
        return $this->Auth->user('id');
    }
    public function getCurrentUserGroupId(){
        $user = $this->getCurrentUser();
        return $user['UserGroup']['groups_id'];
    }
    
    public function getCurrentUser(){
        if (empty (self::$currentUser)){
            $data = $this->User->getUser('first', array(
                    'conditions' => array(
                        'User.id' => $this->getCurrentUserId()
                     )
                ));
            self::$currentUser = $data;
        }
        return self::$currentUser;
    }
    public function getCurrentUserGroup(){
        $data = $this->User->UserGroup->find('first', array(
            'conditions' => array(
                'UserGroup.users_id' => $this->getCurrentUserId()
            ),
            'fields' => array(
                'Group.*'
            )
        ));
               
        return $data;
    }
    
    
    
    public function beforeRender(){
        $this->set('currentUser', $this->getCurrentUser());
        $this->set('currentGroup',$this->getCurrentUserGroup());
    }
    
    public function afterRender(){        
        debug($this->Auth->user());
    }
    
    public function beforeFilter(){
        $this->set('isConnected', ($this->getCurrentUserId() != null));
    
        if ($this->RequestHandler->isAjax()){
            $this->layout = null;
        }
    }
    
    
    static $loadedUsers = array();
    static $currentUser = array();
    
    public function loadUserById($id){
        if (empty(self::$loadedUsers[$id])){
            self::$loadedUsers[$id] = $this->User->getUser('first', array(
                'conditions' => array(
                    'User.id' => $id
                 ),
                'fields' => array(
                    'User.*', 'Image.*'
                )
            ));
        }
        return self::$loadedUsers[$id];
    }
}



?>
